//
//  YMAlbumViewController.swift
//  YMPhotosDemo
//
//  Created by youmy on 2019/12/17.
//  Copyright © 2019 youmy. All rights reserved.
//  列出系统所有相册

import UIKit
import Photos

//相簿列表项
class AlbumItem {
    //相簿名称
    var title:String?
    //相簿内的资源
    var fetchResult:PHFetchResult<PHAsset>
     
    init(title:String?,fetchResult:PHFetchResult<PHAsset>){
        self.title = title
        self.fetchResult = fetchResult
    }
}

private let kCellId = "CellId"

class YMAlbumViewController: UIViewController {
    
    /// 选中相簿时回调
    typealias AlbumReturn = (_ album: AlbumItem)->()
    
    var selAsset: PHAsset!
    
    var seletedAlbum: AlbumReturn?
    
    /// 相簿列表项集合
    var items:[AlbumItem] = []
    
    var tableView : UITableView!
    
    /// 带缓存的图片管理对象
    var imageManager: PHCachingImageManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: view.bounds)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.tableFooterView = UIView()
        
        tableView.register(UINib(nibName: "YMAlbumCell", bundle: nil), forCellReuseIdentifier: kCellId)
        
        view.addSubview(tableView)

        // 申请权限
        PHPhotoLibrary.requestAuthorization { (status) in
            if status != .authorized {
                return
            }
            
            //列出所有系统的智能相册
            let smartOptions = PHFetchOptions()
            let samrtAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: smartOptions)
            
            self.convertCollection(collection: samrtAlbums)
            
            //列出所有用户创建的相册
            let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil)
            self.convertCollection(collection: userCollections as! PHFetchResult<PHAssetCollection>)
            
            //相册按包含的照片数量排序（降序）
            self.items.sort { (item1, item2) -> Bool in
                return item1.fetchResult.count > item2.fetchResult.count
            }
            
            //异步加载表格数据,需要在主线程中调用reloadData() 方法
            DispatchQueue.main.async{
                self.tableView?.reloadData()
            }
            
            // 初始化和重置缓存
            self.imageManager = PHCachingImageManager()
            self.resetCachedAssets()
        }
    }
    
    //重置缓存
    func resetCachedAssets(){
        self.imageManager.stopCachingImagesForAllAssets()
    }
    
    //转化处理获取到的相簿
    private func convertCollection(collection: PHFetchResult<PHAssetCollection>){
        
        for i in 0..<collection.count {
            //获取出但前相簿内的图片
            let resultOptions = PHFetchOptions()
            resultOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            resultOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
            
            let c = collection[i]
            let assetFetchResult = PHAsset.fetchAssets(in: c, options: resultOptions)
            // 没有图片的空相簿不显示
            if assetFetchResult.count > 0 {
                let title = titleOfAlbumForChinse(title: c.localizedTitle)
                items.append(AlbumItem(title: title, fetchResult: assetFetchResult))
            }
        }
    }

    //由于系统返回的相册集名称为英文，我们需要转换为中文
    private func titleOfAlbumForChinse(title:String?) -> String? {
        if title == "Slo-mo" {
            return "慢动作"
        } else if title == "Recently Added" {
            return "最近添加"
        } else if title == "Favorites" {
            return "个人收藏"
        } else if title == "Recently Deleted" {
            return "最近删除"
        } else if title == "Videos" {
            return "视频"
        } else if title == "All Photos" {
            return "所有照片"
        } else if title == "Selfies" {
            return "自拍"
        } else if title == "Screenshots" {
            return "屏幕快照"
        } else if title == "Camera Roll" {
            return "相机胶卷"
        }
        return title
    }
}

extension YMAlbumViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellId) as! YMAlbumCell
        
        let item = self.items[indexPath.row]

        let title = "\(item.title ?? "") \(item.fetchResult.count)"
        
        cell.titleLb?.text = title
        
        guard let asset = item.fetchResult.firstObject else { return cell}
        
        imageManager.requestImage(for: asset, targetSize: CGSize(width: 80, height: 80), contentMode: .aspectFill, options: nil) { (image, info) in
            cell.imageV?.image = image
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let item = self.items[indexPath.row]
        
        selAsset = item.fetchResult.firstObject
        
        seletedAlbum?(item)
        
        performSegue(withIdentifier: "passValue", sender: nil)
    }
}
